import api from '@/api';

const state = {
  // 用户基本信息
  token: '',
  userInfo: null,
  isLogin: false,
  
  // 用户登录状态
  loginType: '', // wechat, phone, account
  
  // 用户权限信息
  permissions: [],
  roles: [],
  
  // 用户设置
  settings: {
    notification: true,
    location: false,
    marketing: false
  },
  
  // 用户交互状态
  interaction: {
    couponActivityClosed: false // 优惠券活动弹窗是否已关闭
  }
};

const mutations = {
  // 设置token
  SET_TOKEN(state, token) {
    state.token = token;
    uni.setStorageSync('token', token);
  },
  
  // 设置用户信息
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo;
    state.isLogin = !!userInfo;
    uni.setStorageSync('userInfo', userInfo);
  },
  
  // 清除用户信息
  CLEAR_USER_INFO(state) {
    state.token = '';
    state.userInfo = null;
    state.isLogin = false;
    state.loginType = '';
    state.permissions = [];
    state.roles = [];
    
    uni.removeStorageSync('token');
    uni.removeStorageSync('userInfo');
  },
  
  // 设置登录类型
  SET_LOGIN_TYPE(state, type) {
    state.loginType = type;
  },
  
  // 更新用户信息
  UPDATE_USER_INFO(state, newInfo) {
    if (state.userInfo) {
      state.userInfo = { ...state.userInfo, ...newInfo };
      uni.setStorageSync('userInfo', state.userInfo);
    }
  },
  
  // 设置权限
  SET_PERMISSIONS(state, permissions) {
    state.permissions = permissions;
  },
  
  // 设置角色
  SET_ROLES(state, roles) {
    state.roles = roles;
  },
  
  // 更新用户设置
  UPDATE_SETTINGS(state, settings) {
    state.settings = { ...state.settings, ...settings };
    uni.setStorageSync('userSettings', state.settings);
  },
  
  // 从本地存储恢复状态
  RESTORE_STATE(state) {
    const token = uni.getStorageSync('token');
    const userInfo = uni.getStorageSync('userInfo');
    const userSettings = uni.getStorageSync('userSettings');
    const couponActivityClosed = uni.getStorageSync('couponActivityClosed');
    
    if (token) {
      state.token = token;
    }
    if (userInfo) {
      state.userInfo = userInfo;
      state.isLogin = true;
    }
    if (userSettings) {
      state.settings = { ...state.settings, ...userSettings };
    }
    if (couponActivityClosed) {
      state.interaction.couponActivityClosed = couponActivityClosed;
    }
  }
};

const actions = {
  // 设置优惠券活动已关闭
  setCouponActivityClosed({ commit }) {
    commit('UPDATE_SETTINGS', { couponActivityClosed: true });
    uni.setStorageSync('couponActivityClosed', true);
  },
  
  // 用户登录
  async login({ commit }, { username, password, type = 'account' }) {
    try {
      const response = await api.user.login({ username, password, type });
      const { token, userInfo } = response.data;
      
      commit('SET_TOKEN', token);
      commit('SET_USER_INFO', userInfo);
      commit('SET_LOGIN_TYPE', type);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('登录失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 手机号登录
  async phoneLogin({ commit }, { phone, code }) {
    try {
      const response = await api.user.phoneLogin({ phone, code });
      if (response.code !== 200) {
        return { success: false, error: response.message };
      }
      const { token, userInfo } = response.data;
      
      commit('SET_TOKEN', token);
      commit('SET_USER_INFO', userInfo);
      commit('SET_LOGIN_TYPE', 'phone');
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('手机登录失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 微信登录
  async wechatLogin({ commit }) {
    try {
      // 获取微信code
      const { code } = await uni.login({ provider: 'weixin' });
      
      const response = await api.user.wechatLogin({ code });
      const { token, userInfo } = response.data;
      
      commit('SET_TOKEN', token);
      commit('SET_USER_INFO', userInfo);
      commit('SET_LOGIN_TYPE', 'wechat');
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('微信登录失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 注册
  async register({ commit }, { username, password, phone, code }) {
    try {
      const response = await api.user.register({ username, password, phone, code });
      return { success: true, data: response.data };
    } catch (error) {
      console.error('注册失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 发送验证码
  async sendSmsCode({ commit }, { phone, type = 'login' }) {
    try {
      const response = await api.user.sendSmsCode({ phone, type });
      return { success: true, data: response.data };
    } catch (error) {
      console.error('发送验证码失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 用户登出
  logout({ commit }) {
    commit('CLEAR_USER_INFO');
    // 清除其他模块的状态
    commit('distribution/CLEAR_DISTRIBUTION_STATE', null, { root: true });
    commit('goods/CLEAR_GOODS_STATE', null, { root: true });
    commit('order/CLEAR_ORDER_STATE', null, { root: true });
    
    uni.reLaunch({
      url: '/pages/index/index'
    });
  },
  
  // 获取用户信息
  async getUserInfo({ commit, state }) {
    try {
      if (!state.token) {
        return { success: false, error: '未登录' };
      }
      
      const response = await api.user.getUserInfo();
      commit('SET_USER_INFO', response.data);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('获取用户信息失败:', error);
      // 如果token过期，清除登录状态
      if (error.code === 401) {
        commit('CLEAR_USER_INFO');
      }
      return { success: false, error: error.message };
    }
  },
  
  // 更新用户信息
  async updateUserInfo({ commit }, userInfo) {
    try {
      const response = await api.user.updateUserInfo(userInfo);
      commit('UPDATE_USER_INFO', userInfo);
      
      return { success: true, data: response.data };
    } catch (error) {
      console.error('更新用户信息失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 修改密码
  async changePassword(_, { oldPassword, newPassword }) {
    try {
      const response = await api.user.changePassword({ oldPassword, newPassword });
      return { success: true, data: response.data };
    } catch (error) {
      console.error('修改密码失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 绑定手机号
  async bindPhone(_, { phone, code }) {
    try {
      const response = await api.user.bindPhone({ phone, code });
      return { success: true, data: response.data };
    } catch (error) {
      console.error('绑定手机号失败:', error);
      return { success: false, error: error.message };
    }
  },
  
  // 初始化用户状态
  initUserState({ commit }) {
    commit('RESTORE_STATE');
  }
};

const getters = {
  // 是否已登录
  isLoggedIn: state => state.isLogin,
  
  // 优惠券活动是否已关闭
  isCouponActivityClosed: state => state.interaction.couponActivityClosed,
  
  // 获取token
  token: state => state.token,
  
  // 获取用户信息
  userInfo: state => state.userInfo,
  
  // 获取用户ID
  userId: state => state.userInfo?.id || null,
  
  // 获取用户名
  userName: state => state.userInfo?.name || state.userInfo?.username || '游客',
  
  // 获取用户头像
  userAvatar: state => state.userInfo?.avatar || '/static/images/default-avatar.png',
  
  // 获取用户手机号
  userPhone: state => state.userInfo?.phone || '',
  
  // 获取登录类型
  loginType: state => state.loginType,
  
  // 检查权限
  hasPermission: state => permission => {
    return state.permissions.includes(permission);
  },
  
  // 检查角色
  hasRole: state => role => {
    return state.roles.includes(role);
  },
  
  // 是否为分销商
  isDistributor: state => {
    return state.roles.includes('distributor') || state.userInfo?.is_distributor;
  },
  
  // 用户设置
  userSettings: state => state.settings
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};